package com.myh.testlogin.common.error404;


import com.myh.testlogin.common.staticnum.StaticConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author 莫耀华
 * @date 2020-09-23 10:50
 * 在定义404请求的json
 */
@Component
public class MyErrorException extends BasicErrorController {


    @Autowired
    public MyErrorException(ErrorAttributes errorAttributes, ServerProperties errorProperties,
                            List<ErrorViewResolver> errorViewResolvers) {
        super(errorAttributes, errorProperties.getError(), errorViewResolvers);
        // TODO Auto-generated constructor stub
    }

    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body=getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
        body.put("msg", "请求路径出现错误,请重试！");
        body.put("data", null);
        body.put("code", StaticConstant.CODE_404);
        body.remove("timestamp");
        body.remove("status");
//        body.remove("error");
        HttpStatus status = getStatus(request);
        return new ResponseEntity<>(body,status);
    }

}
/**
 上面也看到了，springboot 默认把 404 异常交给 BasicErrorController，而我们希望让异常全部交给我们自己处理。

 那么，我们就需要实现 ErrorController 接口
 并且让接口的实现交给 springmvc 管理（添加@Controller注解）
 最后，用 @ControllerAdvice 增强我们的实现类，让他能处理异常
 */